package com.cheyunkeji.er.activity.fast_evaluate;

import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.aspsine.swipetoloadlayout.OnLoadMoreListener;
import com.aspsine.swipetoloadlayout.OnRefreshListener;
import com.cheyun.netsalev3.R;
import com.cheyunkeji.er.Constants;
import com.cheyun.netsalev3.MyApplication;
import com.cheyunkeji.er.adapter.fastevaluate.NoticeAdapter;
import com.cheyunkeji.er.base.BaseActivity;
import com.cheyunkeji.er.bean.fast_evaluate.NoticeBean;
import com.cheyunkeji.er.http.ApiClient;
import com.cheyunkeji.er.http.HttpConstants;
import com.cheyunkeji.er.http.RespCallback;
import com.cheyunkeji.er.view.SToast;
import com.cheyunkeji.er.view.SwipeLayout;
import com.cheyunkeji.er.view.TopBar;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;

public class NoticeActivity extends BaseActivity
    implements AdapterView.OnItemClickListener, OnRefreshListener, OnLoadMoreListener {

  //    当前列表状态 STATE_REFRESH : 下拉刷新 ，STATE_LOADMORE : 上拉加载更多
  private static int CURRENT_REFRESH_STATE = SwipeLayout.STATE_REFRESH;

  //    每页数据量
  private static final int COUNTS_PER_PAGE = 10;

  private int CURRENT_LOAD_PAGE = 1;

  @BindView(R.id.notice_topbar)
  TopBar noticeTopbar;

  @BindView(R.id.ll_empty_content)
  LinearLayout llEmptyContent;

  @BindView(R.id.swipe_target)
  ListView swipeTarget;

  @BindView(R.id.swipe_layout)
  SwipeLayout swipeLayout;

  @BindView(R.id.activity_notice)
  LinearLayout activityNotice;

  private NoticeAdapter adapter;

  private ArrayList<NoticeBean> dataList;

  private Handler uiRefreshHandler =
      new Handler() {

        @Override
        public void handleMessage(Message msg) {

          if (CURRENT_REFRESH_STATE == SwipeLayout.STATE_REFRESH) {

            onRefreshSuccessed((ArrayList<NoticeBean>) msg.obj);
          } else {

            onLoadMoreSuccessed((ArrayList<NoticeBean>) msg.obj);
          }
        }
      };

  @Override
  protected void init() {
    setContentView(R.layout.er_activity_notice);
    ButterKnife.bind(this);
  }

  @Override
  protected void initView() {

    noticeTopbar.setTitle("公告列表");
    noticeTopbar.setLeftBack();
    swipeLayout.setOnRefreshListener(this);
    swipeLayout.setOnLoadMoreListener(this);

    //        根据当前模块选择
    if (MyApplication.getInstance().getCurrentModuleType()
        == Constants.CURRENT_MODULE_TYPE_FAST_EVALUATE) {
      noticeTopbar.setBackgroundColor(getResources().getColor(R.color.bkg_blue));
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        getWindow().setStatusBarColor(getResources().getColor(R.color.bkg_blue));
    } else if (MyApplication.getInstance().getCurrentModuleType()
        == Constants.CURRENT_MODULE_TYPE_FULL_EVALUATE) {
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        getWindow().setStatusBarColor(getResources().getColor(R.color.auction_status_bar));
      noticeTopbar.setBackgroundColor(getResources().getColor(R.color.auction_status_bar));
    } else if (MyApplication.getInstance().getCurrentModuleType()
        == Constants.CURRENT_MODULE_TYPE_AUCTION) {
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        getWindow().setStatusBarColor(getResources().getColor(R.color.auction_status_bar));
      noticeTopbar.setBackgroundColor(getResources().getColor(R.color.auction_status_bar));
    }
  }

  @Override
  protected void initData() {

    dataList = new ArrayList<>();
    adapter = new NoticeAdapter(dataList, this);
    swipeTarget.setAdapter(adapter);
    swipeTarget.setOnItemClickListener(this);
  }

  @Override
  public void onResume() {
    super.onResume();
    swipeLayout.setRefreshing(true);
    onRefresh();
  }

  private void hideEmptyView() {

    // swipeLayout.setVisibility(View.VISIBLE);
    llEmptyContent.setVisibility(View.INVISIBLE);
  }

  private void showContentEmptyView() {

    // swipeLayout.setVisibility(View.INVISIBLE);
    llEmptyContent.setVisibility(View.VISIBLE);
  }

  private void onRefreshSuccessed(ArrayList<NoticeBean> newList) {

    if (newList != null && newList.size() != 0) {

      hideEmptyView();
      dataList.clear();
      dataList.addAll(newList);
      adapter.notifyDataSetChanged();
      CURRENT_LOAD_PAGE++;

    } else if (newList.size() == 0) {
      showContentEmptyView();
      dataList.clear();
      adapter.notifyDataSetChanged();
    }
    swipeLayout.endRefresh();
  }

  /**
   * 上拉加载成功刷新
   *
   * @param newList
   */
  private void onLoadMoreSuccessed(ArrayList<NoticeBean> newList) {

    if (newList != null) {

      if (newList.size() != 0) {

        swipeLayout.endLoadMore();
        dataList.addAll(newList);
        adapter.notifyDataSetChanged();
        CURRENT_LOAD_PAGE++;

      } else {

        swipeLayout.endLoadMore();
        swipeLayout.setLoadMoreEnabled(false);
      }
    }
  }

  private void loadRecordListData(int page, int rows) {

    HashMap<String, String> params = new HashMap<>();
    //      params.put("authkey",
    // UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());//
    // params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(),
    // ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());
    params.put("page", String.valueOf(page));
    params.put("rows", String.valueOf(rows));

    ApiClient.postForm(
        HttpConstants.EVALUATE_NOMAIL_LIST,
        params,
        new RespCallback<ArrayList<NoticeBean>>() {

          @Override
          protected void onRequestFailed(String msg) {
            SToast.show(msg);
          }

          @Override
          protected void onSuccess(ArrayList<NoticeBean> data) {
            Message msg = uiRefreshHandler.obtainMessage();
            msg.obj = data;
            uiRefreshHandler.sendMessage(msg);
          }

          @Override
          public void onError(Exception e) {
            super.onError(e);

            if (CURRENT_REFRESH_STATE == SwipeLayout.STATE_REFRESH) {
              swipeLayout.endRefresh();
            } else if (CURRENT_REFRESH_STATE == SwipeLayout.STATE_LOADMORE) {
              swipeLayout.endLoadMore();
            }
          }
        });
  }

  @Override
  public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    adapter.setPostion(position);
    Intent intent = new Intent(this, NoticeDetailActivity.class);
    intent.putExtra("nid", dataList.get(position).getNid());
    startActivity(intent);
  }

  @Override
  public void onRefresh() {
    CURRENT_REFRESH_STATE = SwipeLayout.STATE_REFRESH;
    CURRENT_LOAD_PAGE = 1;
    loadRecordListData(CURRENT_LOAD_PAGE, COUNTS_PER_PAGE);
    swipeLayout.setLoadMoreEnabled(true);
  }

  @Override
  public void onLoadMore() {
    CURRENT_REFRESH_STATE = SwipeLayout.STATE_LOADMORE;
    loadRecordListData(CURRENT_LOAD_PAGE, COUNTS_PER_PAGE);
  }
}
